
/****根据播放时间调整字幕***/
function swiper_to_page(time){
	var page=0;
	var daly;
	if( swiper_time==2){
		 return;	
	}
	$.each(words_pages,function(i,v){
		var l=$(v).length;
		var s=words_pages[i][0]['start_time_int'];
		var end=words_pages[i][l-1]['end_time_int'];
		if(s<time && time<end){
			page=i;
			daly=end-s;
			return false;
		}
	});
	var all_page=$("#words_content_wrapper .swiper-slide").length;
	var curl_page=$("#words_content_wrapper .swiper-slide").index($(".swiper-slide-active"))+1;
	if(page!=curl_page && page>0 && page<all_page){
		swiper.slideTo(page-1);
	}
}



apiready = function(){
	var fs = api.require('fs');
	fs.readDir({
		path:'fs://movie'
	}, function(ret, err){    
		if( ret.status ){
			var down_movie_file=S('down_movie_file');
			var get_download_enqueue=S("download_enqueue");
			if(down_movie_file==null){
				down_movie_file={};	
			}
			if(get_download_enqueue==null){
				get_download_enqueue={};	
			}
			if($(ret.data).length>0){
				$.each(ret.data,function(i,v){
					var name=v.split(".");
					if(typeof(down_movie_file["down_"+name[0]])=="undefined" || typeof(down_movie_file["down_"+name[0]]['url'])=="undefined"){
						down_movie_file["down_"+name[0]]={};
						get_download_enqueue["down_"+name[0]]={};
					}else{
						var url =down_movie_file["down_"+name[0]]['url'];
						if(url.indexOf("http://")==-1){
							down_movie_file["down_"+name[0]]={};
							get_download_enqueue["down_"+name[0]]={};
						}
					}
				})	
				S('down_movie_file',down_movie_file);
			}else{
				S('down_movie_file',null);
			}
			
		}else{
			//alert( JSON.stringify( err ) );
		}
	});
 //	deviceId 驱动 id
 var deviceId = api.deviceId;
 if(S("con-uuid")==null){	
 	S("con-uuid",deviceId);
	baseUrlArgs['uuid']=deviceId;
	app_init_data=get_param(baseUrlArgs);
 }
 run_app();		
}




function init(page_name){
	if(page_name!=undefined){
		var obj=$("[data-page='"+page_name+"']");	
	}else{
		var obj=$("body");	
		/*****读到历史记录结**/
		S("en_user_data", app_init_data.my_read_words);
		if($("#history_read_word").find("li").length==0 && app_init_data.my_read_words){	 
			load_read_words(app_init_data.my_read_words);
			set_part_id_select(app_init_data.read_detail.part_id);
		}
	}
  /*****下拉菜单***/
  $(".dropup").unbind(hiApp.device.click).bind(hiApp.device.click,function(){
		if($("#history_read_word").find("li").length==0){
			var url=hiApp.params.base_url+"/Index/index/to/1";
			hiApp.router.load_url(url);	
			return false;
		}
		
		if($("[data-page='Index_detail']").length>0){
			var page_cached=$("[data-page='Index_detail']").hasClass('cached');
			if(page_cached){
				hiApp.router.load_name("Index_detail");	
				hiApp.active_toolbar('detail');
				return false;
			}
		}
		var dropdown=$(this).find(".dropdown-toggle");
		if($(dropdown).attr("aria-expanded")=="false"){
			 $(dropdown).parent().addClass("open");
			 $(dropdown).attr("aria-expanded","true");
		}else{
			 $(dropdown).parent().removeClass("open");
			 $(dropdown).attr("aria-expanded","false");
		}
		event.preventDefault();
		event.stopPropagation();
	 })
	 //
	 $("body").unbind(hiApp.device.click).bind(hiApp.device.click,function(){
		 hide_dropdown();
	 })

	
	/*****英文翻译**/
	$(".glyphicon_show_chinese").unbind(hiApp.device.click).bind(hiApp.device.click,function(e){
		$(this).focus();
		show_chinese(this);
		e.stopPropagation();
		e.preventDefault();
		
	})
	/*****播放视频**/
	$(".glyphicon_playerVideoSeek").unbind(hiApp.device.click).bind(hiApp.device.click,function(event){
		$(this).focus();
		clearTimeout(id_of_settimeout_2);
		var player_id=$(this).attr("player");
		var start_time=$(this).attr("start_time_int");
		var end_time=$(this).attr("end_time_int");
		playerVideoSeek(player_id,start_time);
		var d=(end_time-start_time+0.5)*1000;
		id_of_settimeout_2=setTimeout(function(){
			CKobject.getObjectById(player_id).videoPause(); 
		},d);
		event.stopPropagation();
		event.preventDefault();
	})

	$(".eng_word").unbind(hiApp.device.click).bind(hiApp.device.click,function(event){
			$(".popover").remove();
			var text=$(this).text();
			text=text.replace(/[^a-zA-Z]+/gi,'');
			var obj=$(this);
			var url=hiApp.params.base_url+"/Index/show_word";
			baseUrlArgs['word']=text;
			$.get(url,baseUrlArgs,function(data){
				 var options={
					'content':data,
					'placement':'top',
					//'trigger':'click',
					'html':true,
					'title':text,					
				}
				obj.attr("content",text)
				obj.popover(options)
				obj.popover("show");
				var popover_h=$(".popover").height();
				var pop_html=$(".popover").clone();
				$(obj).next(".popover").remove();
			
				var offset_top=$(obj).offset().top-$(pop_html).height()-popover_h;
				//357 281px
				pop_html.css("top",offset_top)
				$("body").append(pop_html);
				$("body").find(".popover").bind(hiApp.device.click,function(event){
					//console.log("touchstart");
					event.stopPropagation();
				});
				$("body").find(".popover").find(".play_mp3").bind(hiApp.device.click,function(event){
					var url=$(this).attr("url");
					play_mp3(url)
				});
				$("body").find(".popover").find(".favorite_eng").bind(hiApp.device.click,function(event){
					var word=$(this).attr("words");
					favorite_eng(word,$(this));
				});
				
				
			});			
			event.preventDefault();
			event.stopPropagation();
			
	});
	
	
	$("body").on(hiApp.device.click,function(event){
		$(".popover").remove();
	})
}

/****正在看选中**/
function set_part_id_select(id){
	$("#history_read_word").find("li").removeClass("active");
	$("#history_read_word").find("[data-id='detail_id_"+id+"']").addClass("active");
}

function load_read_words(_my_read_words_){
	//console.log(_my_read_words_);
 	var html="";
	 if(!_my_read_words_)return;
	// console.log(typeof(_my_read_words_.parts));
	 if($(_my_read_words_.parts).length>0){
	 	var l=_my_read_words_.len;
		var words_id=_my_read_words_.id;
		var files=new Array();
		$.each(_my_read_words_.parts,function(part_id,item){
	 		var key="words_"+words_id+"_"+item.key;
			var data=hiApp.S(key);
			html+='<li class="row" data-id="detail_id_'+item.key+'"> <a class="col-xs-9" localStorage=1  data-type="a" href="/Index/detail/id/'+_my_read_words_.id+'/part_id/'+item.key+'">';
			html+=item.name+'（共'+item.lines+'行';
			if(data){
				html+="，已看"+data.line+"行";
			}
			html+="）";
			html+='</a>';
			//alert(app_params.view_type)
			if(app_params.view_type=="app"){
				var down_id="down_"+words_id+"_"+item.key;
				if(has_down_file(down_id)){
					html+='<div id="'+down_id+'"  class="a2 col-xs-3">本地</div>';
				}else{
					html+=' <div id="'+down_id+'"  class="a2 col-xs-3 download-bnt" data-id="'+_my_read_words_.id+'"  part_id="'+item.key+'" url="'+_my_read_words_.path+'"><span  class="glyphicon glyphicon-download-alt"></span></div>';	
				}
			}
			//alert(html);
			html+="</li>";
		})
		html+='<li role="separator" class="divider"></li>';
        html+=' <li class="last_select"><a  href="/Index/index/to/1" data-type="a" ><span class="a1">'+_my_read_words_.title+'</span>';
		html+=' <span   class="a2" >重选<span  class="glyphicon glyphicon-menu-right"></span></span>';
		html+=' </a>'
		html+='</li>';
	 }
	// console.log(html);
	 $("#history_read_word").html(html);
	// alert(app_params.view_type);
	 hiApp.bind( $("#history_read_word")); 
	 if($("#history_read_word .glyphicon-download-alt").length==0)return;
	 $("#history_read_word .download-bnt").unbind(hiApp.device.click).bind(hiApp.device.click,function(){ 
	 	 event.preventDefault();
		 event.stopPropagation(); 
		var has_down=$(this).attr("has_down");
		if(has_down)return;
		 var url=$(this).attr("url");
		 url+="/"+$(this).attr("part_id")+"_848x476.mp4";
		 var id=$(this).attr("data-id")+"_"+$(this).attr("part_id");
		 var savePath="fs://movie/"+id+".mp4";
		 $(this).attr("has_down",1);
		 down(url,savePath,"down_"+id);
	})
}

function exist_file(files){
	if($(files).length>0){
		$(files).each(function(id,file){
			store_file(file.id)
		})
	}
	
}

/*******重新下载或开始下载*/
function redown(id){
	$("#"+id).html();
}

function has_down_file(id_name){
	var data=S("down_movie_file");	
	if(data==null){
		return false;
	}
	if(typeof(data[id_name])=="undefined"){
		return false;
	}
	if(typeof(data[id_name]['status'])=="undefined"){
		return false;
	}
	return data[id_name];
}

//文件是否在存
function check_exist_file(file,id){
	var fs = api.require('fs');
	fs.exist({
		path: file
	},function(ret,err){
		if( ret.exist ){
		  $("#"+id).attr("has_down",1);
		  $("#"+id).html('本地');
		}
	});
}

//下载
var download_enqueue=S("download_enqueue");
if(download_enqueue==null || download_enqueue==false){
	download_enqueue={};
}
var download_timer;
function down(url,savePath,id){
	var downloadManager = api.require('downloadManager');
	downloadManager.enqueue({
    url: url,
    savePath: savePath,
    cache: true,
    allowResume: true,
    title: '',
    networkTypes: 'wifi '
}, function(ret, err){    
    if( ret ){
		download_enqueue[ret.id]={
				'id':id,
				'finish':0,
		};
		S("download_enqueue",download_enqueue);
		cmd_down_query();
    }else{
        $('#'+id).html( JSON.stringify( err ) );
    }
});
}

//下载进度查询
function cmd_down_query(){
	var count=0;
	download_timer=setInterval(function(){
		if($(download_enqueue).length>0){
			$.each(download_enqueue,function(i,v){
				if(v.finish<100){
					down_query(i,v.id);
					count++;
				}else{
					$("#"+v.id).attr("has_down",1);
					$("#"+v.id).html("本地");
				}
			})	
		}
	},1000);
}
//下载完成
function down_movie_finish(){
	var count=0;
	$.each(download_enqueue,function(i,v){
		if(v.status!=1){
			count++;
		}
	})
	if(count==0){
		clearInterval(download_timer);
	}
}

function down_query(id,div){
	var downloadManager = api.require('downloadManager');
	downloadManager.query({
    ids: [id]
	}, function(ret, err){        
		if( ret ){
			//alert( JSON.stringify( ret ) );
			if($(ret.data).length==0)return;
			var id=ret.data[0].id;
			download_enqueue[id]['status']=ret.data[0].status;
			if(ret.data[0].status==3){
				$('#'+div).html("下载完成");	
				$("#"+div).attr("has_down",1);
				download_enqueue[id]['finish']=100;
				var down_movie_file=S("down_movie_file");
				if(down_movie_file==null){
						down_movie_file={};
				}
				down_movie_file[div]=ret.data[0];
				S('down_movie_file',down_movie_file);
				down_movie_finish();
			}
			if(ret.data[0].status==1){
				var finish=((ret.data[0].finishSize/ret.data[0].totalSize)*100).toFixed(2);
				download_enqueue[id]['finish']=finish;
				$("#"+div).attr("has_down",1);
				$('#'+div).html(finish+"%");	
			}
			if(ret.data[0].status==0){
				$("#"+div).attr("has_down",1);
				$('#'+div).html('等待下载');	
			}
			if(ret.data[0].status==4){
				$("#"+div).attr("has_down",0);
				$('#'+div).html("下载错误");
			}
			if(ret.data[0].status==2){
				$("#"+div).attr("has_down",0);
				$('#'+div).html("暂停");
			}
		}else{
			$('#'+div).html( JSON.stringify( err ) );
		}
	});
}


function hide_dropdown(){
		 $(".dropdown-toggle").parent().removeClass("open");
		  $(".dropdown-toggle").attr("aria-expanded","false");
}
function eng_onAfterShow(param){
	var videos=$("[data-page='"+param.old_page_name+"']").find(".videoPlayer_div");
	//console.log(videos.length);
	if(videos.length>0){
		$.each(videos,function(i,v){
			if($(v).children().eq(0).length>0){
				var player=$(v).children().eq(0).attr("id");
				CKobject.getObjectById(player).videoClear();
			}
		})
	}
	hide_dropdown();
	$(".popover").remove();
}

function show_chinese(_this_){
	$(".popover").remove();
	var chinese=$(_this_).parent().parent().find(".chinese").text();
	var obj=$(_this_).parent().parent();
//	var l=$(obj).parent().find(".list-group-item").index(obj);
	var placement="left";

	var options={
					'content':chinese,
					'placement':placement,
					//'trigger':'click',
					'html':true,
					'title':"",					
				}
	$(_this_).popover(options)
	$(_this_).popover("show");
	
}

/*****收藏到生词本****/
function favorite_eng(word,obj){
	hiApp.showIndicator();
	var data={word:word};
	if(app_params.view_type=="app"){
		data=app_params.urlArgs;
		data['word']=word;
	}
	$.get(base_url+"/Index/add_favorite",data,function(data){
		 hiApp.hideIndicator();
		if(data==1){
			$(obj).css({color:"green","font-size":"18px"});
			/*****删除缓存**/
			var url=base_url+"/Index/notebook";
			var url2=base_url+"/Index/notebook/type/all";
			var url3=base_url+"/Index/notebook/type/new";
			hiApp.removeFromCache(url);
			hiApp.removeFromCache(url2);
			hiApp.removeFromCache(url3);
			$("[data-page='Index_notebook']").remove();
			dialog("成功加入生词本");
		}else{
			dialog(data);	
		}
	})
}




///****监听播放按钮***/
//function loadedHandler(id){
//		console.log(id);
//		//监听播放按钮
//		video_paly_int[id]=0;
//		CKobject.getObjectById(id).addListener('play','playHandler('+id+')');
//  }
// /****播放事件***/ 
// function playHandler(id){
//		if(video_paly_int[id]==0){
//		 	CKobject.getObjectById(id).videoSeek(120);
//			video_paly_int[id]=1;//播放中
//		}
//	} 
//
